package com.hx.thread.condition;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Minghua Chen
 * @date 2020-09-06 10:13
 */
public class MyBlockingQueueForCondition {

    private Queue queue;
    private int max = 16;
    private ReentrantLock lock = new ReentrantLock();
    private Condition notEmpty = lock.newCondition();
    private Condition notFull = lock.newCondition();

    public MyBlockingQueueForCondition(int max) {
        this.max = max;
        queue = new LinkedList();
    }

    public void put(Object object) throws InterruptedException {
        lock.lock();
        try {
            while (queue.size() == max) {
                // 满了  进入阻塞
                notFull.await();
            }
            queue.add(object);
            // 通知消费线程可以进行消费
            notEmpty.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public Object get() throws InterruptedException {
        lock.lock();
        try {
            while (queue.size() == 0) {
                // 为空  进入阻塞
                notEmpty.await();
            }
            Object result = queue.remove();
            // 通知生产线程可以进行消费
            notFull.signalAll();
            return result;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {

    }
}
